package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Message;
import cn.wolfcode.trip.base.mapper.MessageMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IMessageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class MessageServiceImpl implements IMessageService {
    @Autowired
    private MessageMapper messageMapper;

    @Override
    public Map query(Long userId) {
        HashMap<Object, Object> map = new HashMap<>();
        List<Map> noReadMaps = messageMapper.queryForNoReadList(userId);
        List<Map> alreadyReadMaps = messageMapper.queryForAlreadyReadList(userId);
        Integer totleNoRead = messageMapper.queryForCount(userId);
        //合并删除统一发送人
        for(int index1 = 0; index1 < noReadMaps.size();index1++){
            for(int index2 = 0; index2 < alreadyReadMaps.size();index2++){
                if(noReadMaps.get(index1).get("su_id") == alreadyReadMaps.get(index2).get("su_id")){
                    alreadyReadMaps.remove(index2);
                }
            }
        }

        for(Map<Object,Object> obj: alreadyReadMaps) {
            obj.put("num","");
        }
        List<Map> list = new ArrayList<>();
        list.addAll(noReadMaps);
        list.addAll(alreadyReadMaps);



        map.put("list",list);
        map.put("totleNoRead",totleNoRead);
        if(totleNoRead == 0){
            map.put("totleNoRead","");
        }
        return map;
    }
    @Override
    public void setNoReadMsg(Long userId, Long sendUserId) {
        messageMapper.setNoReadMsg(userId,sendUserId);
    }

    @Override
    public List<Message> getMessageContent(Long userId, Long sendUserId) {
        List<Message> sendMessages = messageMapper.getMessageContent(userId,sendUserId);
        List<Message> getMessages = messageMapper.getMessageContent(sendUserId,userId);
        List<Message> messages = new ArrayList<>();
        messages.addAll(sendMessages);
        messages.addAll(getMessages);
        Collections.sort(messages, new Comparator<Message>(){
            @Override
            public int compare(Message o1, Message o2) {
                if(o1.getCreateTime().after(o2.getCreateTime())){
                    return 1;
                }
                if(o1.getCreateTime().equals(o2.getCreateTime())){
                    return 0;
                }
                return -1;
            }
         });
        return messages;
    }

    @Override
    public void save(Message message) {
        message.setCreateTime(new Date());
        message.setState(false);
        messageMapper.insert(message);
    }
}
